const config = require('../../../common/config');
const util = require('../../../utils/util');

/*
*
* 图片上传部分：
* status:0未上传 1已上传 2上传失败
*
* */

var typeId = '';
/**
 * 记录已经上传成功的fileId ，用于去重和保存到门店表:
 * 以下分类仅1张图片有效 ，第二次上传覆盖第一次
 */
var tempLogoFileId = '';
var tempLicenceFileId = '';


Page({
    data: {
        shopName: '',
        isShopNameWarn: false,
        shopAddress: '',
        shopLongitude: 0,
        shopLatitute: 0,
        shopWebsite: '',
        shopIntroduce: '',
        shopIntroduceLength: 0,
        shopBusLisc: '',
        isShopBusLiscWarn: false,
        logoFiles: [],
        logoFilesStatus: [],
        logoFilesUploadProgress:[],
        logoFilesId:[],
        uploadedLogoFileLength: 0,
        busLiscFiles: [],
        busLiscFilesStatus: [],
        busLiscFilesUploadProgress:[],
        busLiscFilesId:[],
        uploadedBusLiscFileLength: 0,

        isAgree: false,
        isNext: false,
        isLoading: false,
        userId: ''

    },
    onLoad: function (opt) {
        wx.setNavigationBarTitle({
            title: '门店发布'
        })
        typeId = opt.typeId;
        util.debug("storepulishstep2js已选择发布门店类型:"+typeId);
        this.setData({
            userId: wx.getStorageSync(config.USER_ID)
        })

    },
    chooseLogoImage: function (e) {
        var that = this;
        wx.chooseImage({
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            count: 1,
            success: function (res) {
                that.setData({
                    logoFiles: res.tempFilePaths,
                    logoFilesStatus: [0],
                    logoFilesUploadProgress:[0]
                });

                const uploadTask = wx.uploadFile({
                    header: {
                        "Content-Type": "multipart/form-data"
                    },
                    url: config.COMMPT_REQPATH + '/uploadFiles',
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    formData: {
                        accessToken: '',
                        refreshToken: '',
                        serviceName: 'wxShopManageService',
                        methodName: 'uploadLogoOrAptitudeImg',
                        reqData: JSON.stringify({fileId:tempLogoFileId})
                    },
                    success: function (res) {
                        var data = JSON.parse(res.data);
                        util.debug("storepushstep2js 文件上传结果：");
                        util.debug(data);
                        if (data.code != 1) {
                            that.setData({
                                logoFilesStatus: [2]
                            });
                        } else {
                            that.setData({
                                logoFilesStatus: [1],
                                logoFilesId:[data.data.fileId],
                                uploadedLogoFileLength : 1,
                                logoFilesUploadProgress: [100]
                            });
                            tempLogoFileId = data.data.fileId;
                        }
                    },
                    fail: function (err) {
                        uploadTask.abort();
                        that.setData({
                            logoFilesStatus: [2]
                        });
                    }
                })

                //此处只能用于debug,具体是否成功不靠谱
                uploadTask.onProgressUpdate((res) => {
                    util.debug('storepushstep2js上传进度:'+ res.progress)
                    util.debug('storepushstep2js已经上传的数据长度:'+res.totalBytesSent)
                    util.debug('storepushstep2js预期需要上传的数据总长度:'+ res.totalBytesExpectedToSend)
                })

            }
        })
    },
    previewLogoImage: function (e) {
        wx.previewImage({
            current: e.currentTarget.id,
            urls: this.data.logoFiles
        })
    },
    chooseBusLiscFilesImage: function (e) {
        var that = this;
        wx.chooseImage({
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            count: 1,
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                    busLiscFiles: res.tempFilePaths,
                    busLiscFilesStatus : [0],
                    busLiscFilesUploadProgress : [0]
                });

                const uploadTask = wx.uploadFile({
                    header: {
                        "Content-Type": "multipart/form-data"
                    },
                    url: config.COMMPT_REQPATH + '/uploadFiles',
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    formData: {
                        accessToken: '',
                        refreshToken: '',
                        serviceName: 'wxShopManageService',
                        methodName: 'uploadLogoOrAptitudeImg',
                        reqData: JSON.stringify({fileId:tempLicenceFileId})
                    },
                    success: function (res) {
                        var data = JSON.parse(res.data);
                        util.debug("storepushstep2js文件上传结果：");
                        util.debug(data);
                        if (data.code != 1) {
                            that.setData({
                                busLiscFilesStatus: [2]
                            });
                        } else {
                            that.setData({
                                busLiscFilesStatus: [1],
                                busLiscFilesId:[data.data.fileId],
                                busLiscFilesUploadProgress: [100],
                                uploadedBusLiscFileLength : 1
                            });
                            tempLicenceFileId = data.data.fileId
                        }
                    },
                    fail: function (err) {
                        uploadTask.abort();
                        that.setData({
                            busLiscFilesStatus: [2]
                        });
                    }
                })

                uploadTask.onProgressUpdate((res) => {
                    util.debug('storepushstep2js上传进度:'+ res.progress)
                    util.debug('storepushstep2js已经上传的数据长度:'+res.totalBytesSent)
                    util.debug('storepushstep2js预期需要上传的数据总长度:'+ res.totalBytesExpectedToSend)
                })

            }
        })
    },
    previewBusLiscFilesImage: function (e) {
        wx.previewImage({
            current: e.currentTarget.id, // 当前显示图片的http链接
            urls: this.data.busLiscFiles // 需要预览的图片http链接列表
        })
    },
    showNext: function (e) {
        var _this = this;
        var isNextCheckPass = true;

        var shopAddress = this.data.shopAddress;
        var shopName = this.data.shopName;
        var shopBusLisc = this.data.shopBusLisc;

        if (shopAddress == '') {
            isNextCheckPass = false;
            //请输入门店地址
        }
        if (shopName == '') {
            isNextCheckPass = false;
            //请输入门店名
            this.setData({
                isShopNameWarn: true
            })
        }
        if (shopBusLisc == '') {
            isNextCheckPass = false;
            //请输入营业执照
            this.setData({
                isShopBusLiscWarn: true
            })
        }

        if(this.data.uploadedBusLiscFileLength == 0){
            isNextCheckPass = false;
            //请上传营业执照
        }

        if(this.data.uploadedLogoFileLength == 0){
            isNextCheckPass = false;
            //请上传门店logo
        }

        var shopWebsite = this.data.shopWebsite;
        var shopIntroduce = this.data.shopIntroduce;
        var shopLongitude=this.data.shopLongitude;
        var shopLatitute = this.data.shopLatitute;
        var isAgree = this.data.isAgree;

        if (isNextCheckPass && isAgree ) {
            wx.showLoading({
                title: '数据加载..',
                icon: 'loading',
                duration: config.TIME_OUT,
                mask:true
            })

            wx.request({
                url: config.COMMPT_REQPATH,
                header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                method:'POST',
                data: {
                    accessToken: '',
                    refreshToken: '',
                    serviceName: 'wxShopManageService',
                    methodName: 'saveShopInfo',
                    reqData:JSON.stringify({
                        shopAddress:shopAddress,
                        shopName:shopName,
                        shopLiscence:shopBusLisc,
                        shopIntroduce:shopIntroduce,
                        shopLongitude:shopLongitude,
                        shopLatitute:shopLatitute,
                        shopTypeId:typeId,
                        shopLogoFileId:tempLogoFileId,
                        shopLicenceFileId:tempLicenceFileId,
                        userId:_this.data.userId
                    })
                },
                success: function (res) {
                    var resultData = res.data;
                    wx.hideLoading();
                    _this.setData({
                        isLoading: false
                    })
                    if(resultData.code == 1){
                        wx.redirectTo({
                            url: '../step3/index?shopId='+resultData.data.shopId
                        })
                    }else{
                        util.debug('storepulishstep2保存店铺信息失败：');
                        util.debug(resultData);
                    }
                },
                fail:function (e) {
                    wx.hideLoading();
                    _this.setData({
                        isLoading: false
                    })
                    util.debug(e.errMsg);
                }
            })

        }


    },
    bindAgreeChange: function (e) {
        if (e.detail.value == 'agree') {
            this.setData({
                isAgree: true,
                isNext: true
            })
        } else {
            this.setData({
                isAgree: false,
                isNext: false
            })
        }
    },
    shopAddressChange: function (e) {
        this.setData({
            shopAddress: e.detail.value
        })
    },
    shopNameChange: function (e) {
        this.setData({
            shopName: e.detail.value
        })
        if (this.data.shopName != '') {
            this.setData({
                isShopNameWarn: false
            })
        }
    },
    shopWebsiteChange:function (e) {
        this.setData({
            shopWebsite:e.detail.value
        })
    },
    chooseLocation: function (e) {
        var _this = this;
        wx.chooseLocation({
            success: function (res) {
                var chooseErr = res.errMsg; //chooseLocation:ok
                var chooseAddress = res.address;
                var chooseLatitute = res.latitude;
                var chooseLongitude = res.longitude;
                var chooseName = res.name; // 地点
                _this.setData({
                    shopLongitude: chooseLongitude,
                    shopLatitute: chooseLatitute,
                    shopAddress: chooseAddress,
                    shopName: chooseName
                })
            },
            fail: function (err) {
                var chooseErr = err.errMsg;//chooseLocation:fail
            }
        })
    },
    shopBusLiscChange: function (e) {
        this.setData({
            shopBusLisc: e.detail.value
        })
        if (this.data.shopBusLisc != '') {
            this.setData({
                isShopBusLiscWarn: false
            })
        }
    },
    shopIntroduceChange: function (e) {
        var shopIntroduceContent = e.detail.value;
        if (shopIntroduceContent.length <= 100) {
            this.setData({
                shopIntroduceLength: shopIntroduceContent.length,
                shopIntroduce: shopIntroduceContent
            })
        }
    },
    openClause:function (e) {
        var content = "门店发布费用及其遵守规范."
        wx.showModal({
            title: '服务条款',
            content: content,
            showCancel:false,
            success: function(res) {
                if (res.confirm) {
                    util.debug("确定条款")
                }
            }
        })
    }
})